﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook;

namespace Skecthial.UI.Controls
{
    public partial class Friends : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpCookie cookie = Request.Cookies["TokenCookie"]; /// it returns a null even if the cookie exisits
            if (cookie != null)
            {
                string TOKEN = cookie.Values["TOKEN"].ToString();
                var accessToken = TOKEN;

                var client = new FacebookClient(accessToken);
                //dynamic result = client.Get("me/friends", new { fields = "name,first_name,middle_name,last_name,id,gender,link,username,birthday,education,email,picture" });
                dynamic result = client.Get("me/friends", new { fields = "name,first_name,middle_name,last_name,id,gender,link,picture" });
                System.Data.DataTable dt = new System.Data.DataTable();
                dt.Columns.Add("name");
                dt.Columns.Add("id");
                dt.Columns.Add("gender");
                dt.Columns.Add("link");
                dt.Columns.Add("picture");
                dt.Columns.Add("first_name");
                dt.Columns.Add("middle_name");
                dt.Columns.Add("last_name");

                for (int i = 0; i < ((Facebook.JsonArray)(((Facebook.JsonObject)result)).Values.ToList()[0]).Count - 280; i++)
                {
                    List<object> personValues = ((Facebook.JsonObject)((Facebook.JsonArray)(((Facebook.JsonObject)result)).Values.ToList()[0])[i]).Values.ToList();
                    List<string> personKeys = ((Facebook.JsonObject)((Facebook.JsonArray)(((Facebook.JsonObject)result)).Values.ToList()[0])[i]).Keys.ToList();
                    DataRow dr = dt.NewRow();
                    for (int p = 0; p < personKeys.Count; p++)
                    {
                        dr[personKeys[p]] = (string)personValues[p];
                    }
                    dt.Rows.Add(dr);
                }
                rptFriends.DataSource = dt;
                rptFriends.DataBind();

                //System.Collections.Generic.Dictionary<string, object> asdd =  result;

                //string asd = (new List<object>(((Facebook.JsonArray)((new System.Collections.Generic.Dictionary<string, object>((result).Values as System.Collections.Generic.Dictionary<string, object>.ValueCollection)).Items[0])))).Items[0];
                //int aaa = (new System.Collections.Generic.Dictionary<string, object>(asdd as IDictionary<string, object>)).Count;

                string id = result.id;
            }
            else
                Response.Redirect("~/pages/login.aspx", false);
        }
    }
}